export const pathHandler = (path) => {
  const arr1 = path.split('.').map(v => [v]);
  arr1.forEach((arr, index) => {
    const pos_start = arr[0].indexOf('[');
    if (pos_start === -1) return;
    arr1[index] = arr[0].replace(/\[|\]\[/g, '.').replace(/\]/g, '').split('.');
  });
  return arr1.reduce((arr, node) => {
    return arr.concat(node);
  }, []);
};

export const dataHandler = (path, value, obj) => {
  const arr = pathHandler(path);
  const len = arr.length;

  let current = obj;
  for (let i = 0; i < len - 1; ++i) {
    const key = arr[i];
    if (!current[key]) throw new Error(`${['$state', ...arr.slice(0, i + 1)].join('.')} net defined.`);
    current = current[key];
  }

  current[arr[len - 1]] = value;
  return obj;
};
